const { verify } = require('../utils/jwt');
const { accessSecret } = require('../config/config.default');
const { User } = require('../model');

module.exports = async (req, res, next) => {
    try {
        const authHeader = req.headers['authorization'];
        const token = authHeader && authHeader.split(' ')[1];
        if (token == null) return res.sendStatus(401);
            const user = await verify(token, accessSecret);
            const users = await User.findById(user.id)
            req.user = users;
            next();
    } catch (err) {
        if (err.name === 'TokenExpiredError') {
            return res.status(401).json({
                code: 401,
                msg: 'token已过期，请重新登录'
            });
        } else if (err.name === 'JsonWebTokenError') {
            return res.status(401).json({
                code: 401,
                msg: 'token已过期，请重新登录'
            });
        } else {
            return res.status(500).send('服务器内部错误');
        }
    }
};
